package com.ttg.common.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttg.common.enums.ErrorCodeEnums;
import lombok.Data;

import java.util.LinkedHashMap;


/**
 * @author ZQ
 * @version 1.0
 * @Description 共用异常
 * @date 2020/11/5 13:32
 */
@Data
public class BaseException extends RuntimeException{
    private static final long serialVersionUID = 5655976018497898188L;
    /**
     * 异常对应的错误类型
     */
    private String errcode;
    private String msg;

    public BaseException() {
    }
    public BaseException(String errmsg) {
        super(toJsonString(ErrorCodeEnums.SYSTEM_ERROR.getErrcode(),errmsg));
        this.errcode=ErrorCodeEnums.SYSTEM_ERROR.getErrcode();
        this.msg=errmsg;
    }
    public BaseException(ErrorCodeEnums exceptionEnum) {
        super(toJsonString(exceptionEnum.getErrcode(),exceptionEnum.getMsg()));
        this.errcode=exceptionEnum.getErrcode();
        this.msg=exceptionEnum.getMsg();
    }

    public BaseException(String errcode , String errmsg) {
        super(toJsonString(errcode,errmsg));
        this.errcode=errcode;
        this.msg=errmsg;
    }

    static String toJsonString(String errcode, String msg){
        LinkedHashMap<String, Object> map = new LinkedHashMap<>(3);
        ObjectMapper objectMapper = new ObjectMapper();
        map.put("errcode", errcode);
        map.put("msg", msg);
        String jsonStr = "";
        try {
            jsonStr = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e){
            e.printStackTrace();
        }
        return jsonStr;
    }
}
